// pkg/host.go - 主机管理模块
package pkg

import (
	"database/sql"
	"fmt"
	"bufio"
	"os"
	"strconv"
	"strings"

	_ "modernc.org/sqlite"
)

// AddHost 添加主机
func (rct *RemoteControlTool) AddHost(host HostInfo) error {
	encryptedPass, err := rct.encrypt(host.Password)
	if err != nil {
		return err
	}
	encryptedRootPass := ""
	if host.RootPass != "" {
		encryptedRootPass, err = rct.encrypt(host.RootPass)
		if err != nil {
			return err
		}
	}
	_, err = rct.DB.Exec("INSERT INTO hosts (ip, port, user, password, root_pass) VALUES (?, ?, ?, ?, ?)",
		host.IP, host.Port, host.User, encryptedPass, encryptedRootPass)
	return err
}

// UpdateHost 修改主机信息
func (rct *RemoteControlTool) UpdateHost(id int, host HostInfo) error {
	encryptedPass, err := rct.encrypt(host.Password)
	if err != nil {
		return err
	}
	encryptedRootPass := ""
	if host.RootPass != "" {
		encryptedRootPass, err = rct.encrypt(host.RootPass)
		if err != nil {
			return err
		}
	}
	_, err = rct.DB.Exec(`UPDATE hosts SET ip=?, port=?, user=?, password=?, root_pass=? WHERE id=?`,
		host.IP, host.Port, host.User, encryptedPass, encryptedRootPass, id)
	return err
}

// DeleteHost 删除主机
func (rct *RemoteControlTool) DeleteHost(id int) error {
	_, err := rct.DB.Exec("DELETE FROM hosts WHERE id=?", id)
	return err
}

// GetHosts 获取所有主机
func (rct *RemoteControlTool) GetHosts() ([]HostInfo, error) {
	rows, err := rct.DB.Query("SELECT id, ip, port, user, password, root_pass FROM hosts")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var hosts []HostInfo
	for rows.Next() {
		var host HostInfo
		var encryptedPass, encryptedRootPass sql.NullString
		err := rows.Scan(&host.ID, &host.IP, &host.Port, &host.User, &encryptedPass, &encryptedRootPass)
		if err != nil {
			return nil, err
		}
		if encryptedPass.Valid {
			decryptedPass, err := rct.decrypt(encryptedPass.String)
			if err != nil {
				return nil, err
			}
			host.Password = decryptedPass
		}
		if encryptedRootPass.Valid && encryptedRootPass.String != "" {
			decryptedRootPass, err := rct.decrypt(encryptedRootPass.String)
			if err != nil {
				return nil, err
			}
			host.RootPass = decryptedRootPass
		}
		hosts = append(hosts, host)
	}
	return hosts, nil
}

// GetHostByID 根据ID获取主机
func (rct *RemoteControlTool) GetHostByID(id int) (*HostInfo, error) {
	row := rct.DB.QueryRow("SELECT id, ip, port, user, password, root_pass FROM hosts WHERE id = ?", id)
	var host HostInfo
	var encryptedPass, encryptedRootPass sql.NullString
	err := row.Scan(&host.ID, &host.IP, &host.Port, &host.User, &encryptedPass, &encryptedRootPass)
	if err != nil {
		return nil, err
	}
	if encryptedPass.Valid {
		decryptedPass, err := rct.decrypt(encryptedPass.String)
		if err != nil {
			return nil, err
		}
		host.Password = decryptedPass
	}
	if encryptedRootPass.Valid && encryptedRootPass.String != "" {
		decryptedRootPass, err := rct.decrypt(encryptedRootPass.String)
		if err != nil {
			return nil, err
		}
		host.RootPass = decryptedRootPass
	}
	return &host, nil
}

// ImportHostsFromTxt 从txt文件导入主机
func (rct *RemoteControlTool) ImportHostsFromTxt(filePath string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	var hosts []HostInfo

	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		parts := strings.Split(line, ",")
		if len(parts) < 4 {
			continue
		}

		port := 22
		if len(parts) > 1 {
			fmt.Sscanf(parts[1], "%d", &port)
		}

		host := HostInfo{
			IP:       strings.TrimSpace(parts[0]),
			Port:     port,
			User:     strings.TrimSpace(parts[2]),
			Password: strings.TrimSpace(parts[3]),
			RootPass: "",
		}

		if len(parts) > 4 {
			host.RootPass = strings.TrimSpace(parts[4])
		}

		hosts = append(hosts, host)
	}

	if len(hosts) == 0 {
		return fmt.Errorf("文件中没有找到有效的主机信息")
	}

	return rct.ImportHosts(hosts)
}

// ImportHosts 导入主机列表
func (rct *RemoteControlTool) ImportHosts(hosts []HostInfo) error {
	tx, err := rct.DB.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()

	stmt, err := tx.Prepare("INSERT INTO hosts (ip, port, user, password, root_pass) VALUES (?, ?, ?, ?, ?)")
	if err != nil {
		return err
	}
	defer stmt.Close()

	for _, host := range hosts {
		encryptedPass, err := rct.encrypt(host.Password)
		if err != nil {
			return err
		}
		encryptedRootPass := ""
		if host.RootPass != "" {
			encryptedRootPass, err = rct.encrypt(host.RootPass)
			if err != nil {
				return err
			}
		}
		_, err = stmt.Exec(host.IP, host.Port, host.User, encryptedPass, encryptedRootPass)
		if err != nil {
			return err
		}
	}

	return tx.Commit()
}

// ParseHostSelection 解析主机选择
func (rct *RemoteControlTool) ParseHostSelection(selection string) ([]int, error) {
	hosts, err := rct.GetHosts()
	if err != nil {
		return nil, err
	}
	if len(hosts) == 0 {
		return nil, fmt.Errorf("没有配置任何主机")
	}

	parts := strings.Split(selection, ",")
	var hostIDs []int

	for _, part := range parts {
		part = strings.TrimSpace(part)
		if strings.Contains(part, "-") {
			rangeParts := strings.Split(part, "-")
			if len(rangeParts) != 2 {
				return nil, fmt.Errorf("无效的范围格式: %s", part)
			}
			start, err1 := strconv.Atoi(strings.TrimSpace(rangeParts[0]))
			end, err2 := strconv.Atoi(strings.TrimSpace(rangeParts[1]))
			if err1 != nil || err2 != nil {
				return nil, fmt.Errorf("无效的范围数字: %s", part)
			}
			if start > end {
				start, end = end, start
			}
			for i := start; i <= end; i++ {
				hostIDs = append(hostIDs, i)
			}
		} else {
			id, err := strconv.Atoi(part)
			if err != nil {
				return nil, fmt.Errorf("无效的主机ID: %s", part)
			}
			hostIDs = append(hostIDs, id)
		}
	}
	return hostIDs, nil
}


